import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Polygon;
import java.util.List;
import java.util.Map;

import com.speljohan.rsbot.accessors.NPC;
import com.speljohan.rsbot.accessors.Player;
import com.speljohan.rsbot.bot.Bot;
import com.speljohan.rsbot.event.events.ServerMessageEvent;
import com.speljohan.rsbot.event.listeners.PaintListener;
import com.speljohan.rsbot.event.listeners.ServerMessageListener;
import com.speljohan.rsbot.script.Calculations;
import com.speljohan.rsbot.script.Script;
import com.speljohan.rsbot.script.Skills;
import com.speljohan.rsbot.script.wrappers.RSCharacter;
import com.speljohan.rsbot.script.wrappers.RSInterface;
import com.speljohan.rsbot.script.wrappers.RSItemTile;
import com.speljohan.rsbot.script.wrappers.RSNPC;
import com.speljohan.rsbot.script.wrappers.RSPlayer;
import com.speljohan.rsbot.script.wrappers.RSTile;

public class GarrettSoulWars extends Script implements ServerMessageListener, PaintListener {
	
	private String lastClanMessage = null;
	private int redClanCount = 0;
	private int blueClanCount = 0;
	private boolean continueChat = true;
	
	private class ClanChat implements Runnable {	
		
		Thread t;

		public void init()	
		{	
			t = new Thread(this);
			t.start();
		}

		@SuppressWarnings("static-access")
		public void run()
		{
			while(continueChat)
			{
				if (RSInterface.getInterface(836).getChild(27).isValid() && clanChat)
				{
					String timer = RSInterface.getInterface(836).getChild(27).getText();
					if (timer.equals("2 mins") || timer.equals("1 min"))
					{
						String currentClanMessage[] = {"line 0", RSInterface.getInterface(137).getChild(157).getText(),RSInterface.getInterface(137).getChild(156).getText(),RSInterface.getInterface(137).getChild(155).getText(),RSInterface.getInterface(137).getChild(154).getText(),RSInterface.getInterface(137).getChild(153).getText(),RSInterface.getInterface(137).getChild(152).getText()};
						for (int i = 0; i <= 6; i++) {
							if (currentClanMessage[i].contains("<col=800000>"))
							{
								if (currentClanMessage[i] != lastClanMessage)
								{
									if (currentClanMessage[i].contains("Red") || currentClanMessage[i].contains("red") || currentClanMessage[i].contains("R E D"))
									{
										redClanCount++; 
									}
									if (currentClanMessage[i].contains("Blue") || currentClanMessage[i].contains("blue") || currentClanMessage[i].contains("B L U E"))
									{
										blueClanCount++; 
									}
									lastClanMessage = currentClanMessage[i];
								}
							}
						}
					}
				}
				try {
					t.sleep(10);
				} catch (InterruptedException e) {}
			}
		}
	}
	
	private String optionJOIN = null;
	private boolean optionCAPTURE = false;
	private boolean optionFIGHT = false;
	private boolean optionBONES = false;
	private boolean optionSHARDS = false;
	private boolean optionSPECIAL = false;
	private boolean optionRETRI = false;
	private boolean optionREDEM = false;
	private boolean optionSMITE = false;
	private boolean optionCHIVA = false;
	private boolean optionPIETY = false;
	private boolean smartSwitch = false;
	private String myLastTeam = null;
	private String lastWon = null;
	private String currentTeam = null;
	private String controlObelisk = null;
	private String controlWestern = null;
	private String controlEastern = null;
	private String playerPosition = null;
	private String theLoc = null;
	private String inGameMethod = null;
	private String teamMethod = null;
	private long scriptStartTime;
	private int randomize = 0;
	private int doWhat = 0;
	private int zealGained = 0;
	//TODO
	private int[] soulShardID = {14639};
	private int[] bonesID = {14638};
	private int countSoulShards = 0;
	private int randomSoulShards = 0;
	private int randomBones = 0;
	private int slayerLevel = 0;
	private int gamesCompleted = 0;
	private int countRedTeam = 0;
	private int countBlueTeam = 0;
	private int deathCount = 0;
	private int[] pyrefiend = {8598};
	private int[] jelly = {8599};
	private int[] barricade = {8600,8601};
	private boolean clanChat = false;
	private boolean smartJoin = false;
	private boolean leftSpawn = false;
	private boolean onlyBalance = false;
	private boolean onlyRed = false;
	private boolean onlyBlue = false;
	private boolean onlyWinners = false;
	private boolean onlyLosers = false;
	private boolean attackPyre = false;
	private boolean attackJelly = false;
	private boolean inGame = false;
	private boolean inWaitArea = false;
	private boolean multipleActions = false;
	private RSTile ToRed[] = {new RSTile(1890, 3162), new RSTile(1900, 3162)};
	private RSTile ToBlue[] = {new RSTile(1890, 3162), new RSTile(1880, 3162)};
	private RSTile ToBalance[] = {new RSTile(1890, 3162)};
	private RSTile RedEntrance = new RSTile(1900, 3162);
	private RSTile BlueEntrance = new RSTile(1879, 3162);
	private RSTile BalanceEntrance = new RSTile(1890, 3162);
	private RSTile obeliskTile = new RSTile(1885, 3231);
	private RSTile eastGraveTile = new RSTile(1933, 3243);
	private RSTile westGraveTile = new RSTile(1842, 3220);
	
	private int outsideX[] = new int[]{1899,1902,1880,1880,1882,1895};
	private int outsideY[] = new int[]{3162,3174,3170,3161,3154,3157};
	private Polygon outside = new Polygon(outsideX, outsideY, 6);
	
	private int redAreaX[] = new int[]{1900,1901,1908,1909,1909,1908,1901,1900};
	private int redAreaY[] = new int[]{3165,3166,3166,3165,3158,3157,3157,3158};
	private Polygon redArea = new Polygon(redAreaX, redAreaY, 8);
	
	private int blueAreaX[] = new int[]{1880,1880,1880,1879,1879,1878,1871,1870,1870,1872,1871,1878,1879,1879};
	private int blueAreaY[] = new int[]{3162,3161,3163,3162,3159,3158,3158,3159,3165,3166,3166,3166,3165,3160};
	private Polygon blueArea = new Polygon(blueAreaX, blueAreaY, 14);
	
	private int randomRedX[] = new int[]{1901,1902,1903,1904,1905,1906,1907,1907,1908,1908,1908,1908,1908,1908,1907,1907,1902,1903,1904,1905,1905,1905,1904,1903,1902,1901,1901};
	private int randomRedY[] = new int[]{3164,3165,3165,3165,3165,3165,3165,3164,3164,3163,3162,3161,3160,3159,3159,3158,3159,3158,3158,3158,3159,3160,3161,3161,3161,3161,3160};
	
	private int randomBlueX[] = new int[]{1879,1878,1878,1878,1878,1877,1877,1877,1876,1874,1872,1874,1873,1871,1872,1874,1874,1876,1873,1871,1871,1875,1873,1875,1876,1876,1877};
	private int randomBlueY[] = new int[]{3164,3163,3162,3161,3160,3160,3161,3163,3164,3164,3164,3165,3164,3163,3162,3161,3161,3161,3160,3161,3160,3159,3159,3160,3161,3160,3159};

	//OBELISK
	private int obeliskX[] = new int[]{1880,1892,1893,1881};
	private int obeliskY[] = new int[]{3224,3224,3238,3238};
	private Polygon obelisk = new Polygon(obeliskX, obeliskY, 4);
	
	//EAST GRAVEYARD
	private int eastGraveyardX[] = new int[]{1939,1927,1929,1938};
	private int eastGraveyardY[] = new int[]{3251,3251,3240,3240};
	private Polygon eastGraveyard = new Polygon(eastGraveyardX, eastGraveyardY, 4);
	
	//WEST GRAVEYARD
	private int westGraveyardX[] = new int[]{1836,1846,1848,1837};
	private int westGraveyardY[] = new int[]{3212,3213,3224,3224};
	private Polygon westGraveyard = new Polygon(westGraveyardX, westGraveyardY, 4);
	
	//WEST PYRE
	private int westPyreX[] = new int[]{1838,1857,1855,1837};
	private int westPyreY[] = new int[]{3240,3240,3257,3256};
	private Polygon westPyre = new Polygon(westPyreX, westPyreY, 4);
	
	//EAST PYRE
	private int eastPyreX[] = new int[]{1918,1920,1928,1934,1938,1936};
	private int eastPyreY[] = new int[]{3220,3206,3203,3206,3213,3220};
	private Polygon eastPyre = new Polygon(eastPyreX, eastPyreY, 6);
	
	//BLUE HOME
	private int blueHomeX[] = new int[]{1816,1823,1823,1816};
	private int blueHomeY[] = new int[]{3220,3220,3230,3230};
	private Polygon blueHome = new Polygon(blueHomeX, blueHomeY, 4);
	
	//RED HOME
	private int redHomeX[] = new int[]{1959,1959,1952,1952};
	private int redHomeY[] = new int[]{3244,3234,3234,3244};
	private Polygon redHome = new Polygon(redHomeX, redHomeY, 4);
	
	//BLUE AVATAR
	private int blueAvatarX[] = new int[]{1808,1812,1812,1808,1803,1801,1802};
	private int blueAvatarY[] = new int[]{3217,3213,3208,3206,3206,3210,3215};
	private Polygon blueAvatar = new Polygon(blueAvatarX, blueAvatarY, 7);
	
	//RED AVATAR
	private int redAvatarX[] = new int[]{1962,1971,1971,1962};
	private int redAvatarY[] = new int[]{3247,3247,3256,3256};
	private Polygon redAvatar = new Polygon(redAvatarX, redAvatarY, 4);
	
	//NORTH JELLY
	private int northJellyX[] = new int[]{1887,1887,1909,1907};
	private int northJellyY[] = new int[]{3247,3258,3255,3244};
	private Polygon northJelly = new Polygon(northJellyX, northJellyY, 4);
	
	//SOUTH JELLY
	private int southJellyX[] = new int[]{1873,1889,1890,1873};
	private int southJellyY[] = new int[]{3204,3201,3215,3216};
	private Polygon southJelly = new Polygon(southJellyX, southJellyY, 4);
	
	//WEST GRAVEYARD PATHS
	private RSTile graveWestToWestPyre[] = {new RSTile(1845, 3231),new RSTile(1849, 3242),new RSTile(1849, 3242)};
	private RSTile graveWestToNorthJelly[] = {new RSTile(1849, 3230),new RSTile(1858, 3239),new RSTile(1867, 3248),new RSTile(1877, 3253),new RSTile(1890, 3251)};
	private RSTile graveWestToSouthJelly[] = {new RSTile(1855, 3218),new RSTile(1865, 3211),new RSTile(1875, 3207),new RSTile(1883, 3207)};
	private RSTile graveWestToObelisk[] = {new RSTile(1853, 3226),new RSTile(1864, 3234),new RSTile(1875, 3233),new RSTile(1885, 3231)};
	
	//EAST GRAVEYARD PATHS
	private RSTile graveEastToEastPyre[] = {new RSTile(1925, 3232),new RSTile(1926, 3221),new RSTile(1928, 3212)};
	private RSTile graveEastToNorthJelly[] = {new RSTile(1920, 3245),new RSTile(1911, 3247),new RSTile(1903, 3250),new RSTile(1897, 3250)};
	private RSTile graveEastToSouthJelly[] = {new RSTile(1926, 3231),new RSTile(1918, 3223),new RSTile(1910, 3214),new RSTile(1899, 3211),new RSTile(1889, 3207),new RSTile(1882, 3207)};
	private RSTile graveEastToObelisk[] = {new RSTile(1924, 3233),new RSTile(1913, 3231),new RSTile(1903, 3230),new RSTile(1894, 3232),new RSTile(1887, 3231)};
	
	//NORTH JELLY PATHS
	private RSTile jellyNorthToWestGrave[] = {new RSTile(1878, 3250),new RSTile(1867, 3245),new RSTile(1858, 3236),new RSTile(1850, 3229),new RSTile(1842, 3220)};
	private RSTile jellyNorthToEastGrave[] = {new RSTile(1908, 3250),new RSTile(1917, 3246),new RSTile(1925, 3245),new RSTile(1933, 3243)};
	private RSTile jellyNorthToWestPyre[] = {new RSTile(1891, 3252),new RSTile(1882, 3252),new RSTile(1873, 3251),new RSTile(1862, 3250),new RSTile(1854, 3247),new RSTile(1844, 3247)};
	
	//SOUTH JELLY PATHS
	private RSTile jellySouthToWestGrave[] = {new RSTile(1872, 3211),new RSTile(1861, 3214),new RSTile(1851, 3218),new RSTile(1844, 3219)};
	private RSTile jellySouthToEastGrave[] = {new RSTile(1890, 3209),new RSTile(1899, 3213),new RSTile(1908, 3218),new RSTile(1918, 3225),new RSTile(1929, 3232),new RSTile(1933, 3243)};
	private RSTile jellySouthToEastPyre[] = {new RSTile(1890, 3208),new RSTile(1899, 3211),new RSTile(1907, 3214),new RSTile(1915, 3214),new RSTile(1923, 3212)};
	
	//WEST PYRE PATHS
	private RSTile pyreWestToWestGrave[] = {new RSTile(1844, 3231),new RSTile(1842, 3220)};
	private RSTile pyreWestToObelisk[] = {new RSTile(1848, 3243),new RSTile(1855, 3236),new RSTile(1865, 3233),new RSTile(1875, 3233),new RSTile(1885, 3231)};
	
	//EAST PYRE PATHS
	private RSTile pyreEastToEastGrave[] = {new RSTile(1928, 3223),new RSTile(1929, 3230),new RSTile(1933, 3238),new RSTile(1933, 3243)};
	private RSTile pyreEastToObelisk[] = {new RSTile(1923, 3221),new RSTile(1919, 3227),new RSTile(1910, 3231),new RSTile(1900, 3231),new RSTile(1892, 3231),new RSTile(1888, 3231)};
	
	//RED HOME PATHS (we are east)
	private RSTile redToEastGrave[] = {new RSTile(1967, 3229),new RSTile(1966, 3220),new RSTile(1959, 3212),new RSTile(1950, 3217),new RSTile(1938, 3222),new RSTile(1936, 3232), new RSTile(1933, 3243)};
	private RSTile redToEastPyre[] = {new RSTile(1967, 3232),new RSTile(1966, 3220),new RSTile(1958, 3211),new RSTile(1951, 3215),new RSTile(1942, 3222),new RSTile(1931, 3218),new RSTile(1924, 3211)};
	private RSTile redToNorthJelly[] = {new RSTile(1967, 3233),new RSTile(1965, 3224),new RSTile(1960, 3212),new RSTile(1953, 3216),new RSTile(1944, 3220),new RSTile(1934, 3226),new RSTile(1923, 3232),new RSTile(1913, 3238),new RSTile(1908, 3246),new RSTile(1899, 3250)};
	private RSTile redToObelisk[] = {new RSTile(1967, 3230),new RSTile(1966, 3219),new RSTile(1956, 3211),new RSTile(1946, 3218),new RSTile(1935, 3224),new RSTile(1921, 3225),new RSTile(1911, 3231),new RSTile(1902, 3231),new RSTile(1894, 3231),new RSTile(1887, 3232)};
	
	//BLUE HOME PATHS (we are west)
	private RSTile blueToWestGrave[] = {new RSTile(1806, 3234), new RSTile(1810, 3246), new RSTile(1823, 3245), new RSTile(1832, 3236), new RSTile(1842, 3229)};
	private RSTile blueToWestPyre[] = {new RSTile(1806, 3230),new RSTile(1808, 3240),new RSTile(1815, 3247),new RSTile(1825, 3244),new RSTile(1835, 3244),new RSTile(1844, 3244),new RSTile(1849, 3248)};
	private RSTile blueToSouthJelly[] = {new RSTile(1808, 3229),new RSTile(1807, 3239),new RSTile(1813, 3248),new RSTile(1820, 3247),new RSTile(1826, 3242),new RSTile(1834, 3235),new RSTile(1843, 3231),new RSTile(1852, 3227),new RSTile(1857, 3219),new RSTile(1864, 3213),new RSTile(1872, 3210),new RSTile(1881, 3208)};
	private RSTile blueToObelisk[] = {new RSTile(1806, 3234), new RSTile(1810, 3246), new RSTile(1823, 3245), new RSTile(1832, 3241), new RSTile(1843, 3234), new RSTile(1857, 3233), new RSTile(1870, 3233), new RSTile(1882, 3232)};
	
	//OBELISK PATHS
	private RSTile obeliskToWestGrave[] = {new RSTile(1878, 3233),new RSTile(1878, 3233),new RSTile(1870, 3233),new RSTile(1858, 3234),new RSTile(1849, 3227),new RSTile(1843, 3219)};
	private RSTile obeliskToEastGrave[] = {new RSTile(1897, 3231),new RSTile(1907, 3231),new RSTile(1918, 3232),new RSTile(1930, 3234),new RSTile(1933, 3241)};
	
	public String getAuthor() {
		return "Garrett";
	}

	public String getName() {
    	return "Garrett's Soul Wars";
	}

	public String getScriptCategory() {
    	return "Garrett";
	}
    
	public double getVersion() {
    	return 1.03;
	}
    
	public String getScriptDescription() {
    	String html = "<html><head>";
        html += "</head><body>";
        html += "<center><strong><h2>" + getName() + " v" + getVersion() + "</h2></strong></center>";
        html += "<center>Start the script near the Blance Portal area.</center>";
        html += "<strong>What team should we join?</strong><br />";
        html += "<select name='optionJOIN'>";
        html += "<option>CLAN CHAT";
        html += "<option>SMART JOIN";
        html += "<option>Won Last";
        html += "<option>Lost Last";
        html += "<option>Balance";
        html += "<option>Join Blue";
        html += "<option>Join Red</select><br />";
        html += "<input name='smartSwitch' type='checkbox' value='1'>Smart Switch<br /><br />";
        html += "<strong>What should we do during the game? (You can select more than one)</strong><br />";
        html += "<input name='optionCAPTURE' type='checkbox' value='1'>AFK<br />";
        html += "<input name='optionFIGHT' type='checkbox' value='1'>Fight Monsters<br />";
        //html += "<input name='optionBONES' type='checkbox' value='1'>Collect/Bury Bones<br />";
        //html += "<input name='optionSHARDS' type='checkbox' value='1'>Collect/Use Soul Shards<br /><br />";
        //html += "<strong>Do you want to use prayer or special attack while fighting?</strong>";
        //html += "<table border='0'><tr><td>";
        //html += "<input name='optionSPECIAL' type='checkbox' value='1'>Special Attack<br />";
        //html += "<input name='optionRETRI' type='checkbox' value='1'>Retribution<br />";
        //html += "<input name='optionREDEM' type='checkbox' value='1'>Redemption<br />";
        //html += "</td><td>";
        //html += "<input name='optionSMITE' type='checkbox' value='1'>Smite<br />";
        //html += "<input name='optionCHIVA' type='checkbox' value='1'>Chivalry<br />";
        //html += "<input name='optionPIETY' type='checkbox' value='1'>Piety";
        //html += "</td></tr>";
        html += "<br /><br /><strong>Clan Chat Mode:</strong> Please join the Clan Chat before starting the script.";
        html += "</body></html>";
        html += "";
        return html;
	}

	public boolean onStart(Map<String, String> args) {
		optionJOIN = args.get("optionJOIN");
		optionCAPTURE = args.get("optionCAPTURE") != null ? true : false;
		optionFIGHT = args.get("optionFIGHT") != null ? true : false;
		optionBONES = args.get("optionBONES") != null ? true : false;
		optionSHARDS = args.get("optionSHARDS") != null ? true : false;
		optionSPECIAL = args.get("optionSPECIAL") != null ? true : false;
		optionRETRI = args.get("optionRETRI") != null ? true : false;
		optionREDEM = args.get("optionREDEM") != null ? true : false;
		optionSMITE = args.get("optionSMITE") != null ? true : false;
		optionCHIVA = args.get("optionCHIVA") != null ? true : false;
		optionPIETY = args.get("optionPIETY") != null ? true : false;
		smartSwitch = args.get("smartSwitch") != null ? true : false;
		
		if (optionCAPTURE)
			inGameMethod = "AFK";
		else if (optionFIGHT)
			inGameMethod = "Fight";
		else if (optionFIGHT && optionCAPTURE)
			inGameMethod = "AFK & Fight";
		
		if (optionJOIN.equals("CLAN CHAT"))
		{
			clanChat = true;
			new ClanChat().init();
			teamMethod = "Clan Chat";
		}
		else if (optionJOIN.equals("SMART JOIN"))
		{
			smartJoin = true;
			teamMethod = "Smart Join";
		}
		else if (optionJOIN.equals("Won Last"))
		{
			onlyWinners = true;
			teamMethod = "Last Winners";
		}
		else if (optionJOIN.equals("Lost Last"))
		{
			onlyLosers = true;
			teamMethod = "Last Losers";
		}
		else if (optionJOIN.equals("Balance"))
		{
			onlyBalance = true;
			teamMethod = "Balance";
		}
		else if (optionJOIN.equals("Join Blue"))
		{
			onlyBlue = true;
			teamMethod = "Blue Only";
		}
		else if (optionJOIN.equals("Join Red"))
		{
			onlyRed = true;
			teamMethod = "Red Only";
		}
		else {
			log("Team Selection Error!");
			return false;
		}
        scriptStartTime = System.currentTimeMillis();
		return true;
	}
    
	public void onFinish() {
		continueChat = false;
		Bot.getEventManager().removeListener(PaintListener.class, this);
		Bot.getEventManager().removeListener(ServerMessageListener.class, this);   
	}
	
	public int loop() {
		
		runthisfirst();
		
		clickContinue();
		
        checktheTeam();

        checktheTeam2();

		jointheTeam();
		
		inwaitArea();

		leavetheSpawn();
		
		if (inGame)
		{
			
			if (slayerLevel == 0)
				slayerLevel = getSlayerLevel();
			
			if (deathCount >= 5 && optionFIGHT && optionCAPTURE)
			{
				randomize = random(1,3);
				if (randomize == 1)
					log("We will fight.");
				if (randomize == 2)
					log("We will go AFK.");
				deathCount = 0;
			}
			
			if (optionFIGHT && optionCAPTURE && randomize == 0)
			{
				multipleActions = true;
				randomize = random(1,3);
				if (randomize == 1)
					log("We will fight.");
				if (randomize == 2)
					log("We will go AFK.");
			}
			
			if ((optionFIGHT && !multipleActions) || randomize == 1)
			{
				if (slayerLevel < 30)
				{
					log("You need to have a 30+ Slayer to fight monsters.");
					log("Fight Monsters has been disabled. AFK mode enabled.");
					optionFIGHT = false;
					optionCAPTURE = true;
					multipleActions = false;
					randomize = 0;
					return random(50,150);
				}
				
				if (slayerLevel >= 52)
				{
					if (currentTeam == "Blue")
					{
						if (theLoc == "westGrave")
						{
							letsFight(new RSTile(1883, 3207), graveWestToSouthJelly, jelly, "Attack Jelly");
						}
						else if (theLoc == "eastGrave")
						{
							letsFight(new RSTile(1897, 3250), graveEastToNorthJelly, jelly, "Attack Jelly");
						}
						else
						{
							letsFight(new RSTile(1883, 3207), blueToSouthJelly, jelly, "Attack Jelly");
						}
					}	
					
					if (currentTeam == "Red")
					{
						if (theLoc == "westGrave")
						{
							letsFight(new RSTile(1883, 3207), graveWestToSouthJelly, jelly, "Attack Jelly");
						}
						else if (theLoc == "eastGrave")
						{
							letsFight(new RSTile(1897, 3250), graveEastToNorthJelly, jelly, "Attack Jelly");
						}
						else
						{
							letsFight(new RSTile(1897, 3250), redToNorthJelly, jelly, "Attack Jelly");
						}
					}
					return random(50,150);
				}
				
				if (slayerLevel >= 30)
				{
					
					if (currentTeam == "Blue")
					{
						if (theLoc == "westGrave")
						{
							letsFight(new RSTile(1849, 3248), graveWestToWestPyre, pyrefiend, "Attack Pyrefiend");
						}
						else if (theLoc == "eastGrave")
						{
							letsFight(new RSTile(1924, 3211), graveEastToEastPyre, pyrefiend, "Attack Pyrefiend");
						}
						else
						{
							letsFight(new RSTile(1849, 3248), blueToWestPyre, pyrefiend, "Attack Pyrefiend");
						}
					}
				
					if (currentTeam == "Red")
					{
						if (theLoc == "westGrave")
						{
							letsFight(new RSTile(1849, 3248), graveWestToWestPyre, pyrefiend, "Attack Pyrefiend");
						}
						else if (theLoc == "eastGrave")
						{
							letsFight(new RSTile(1924, 3211), graveEastToEastPyre, pyrefiend, "Attack Pyrefiend");
						}
						else
						{
							letsFight(new RSTile(1924, 3211), redToEastPyre, pyrefiend, "Attack Pyrefiend");
						}
					}
					return random(50,150);
				}
			}
			if ((optionCAPTURE && !multipleActions) || randomize == 2)
			{
				
				if (distanceTo(new RSTile(1933, 3243)) <= 10)
				{
					antiBan2();
					wait(random(4000,6000));
					randomAFK();
					return random(50,150);
				}
				
				if (distanceTo(new RSTile(1842, 3229)) <= 10)
				{
					antiBan2();
					wait(random(4000,6000));
					randomAFK();
					return random(50,150);
				}
				
				if (currentTeam == "Red")
				{
					if (anotherRand == 1 || anotherRand == 0)
					{
						letsAFK(new RSTile(1933, 3243), redToEastGrave, true);
					}
					else if (anotherRand == 2)
					{
						letsAFK(new RSTile(1887, 3232), redToObelisk, true);
					}
					else if (anotherRand == 3)
					{
						letsAFK(new RSTile(1967, 3238), null, false);
					}
				}
				if (currentTeam == "Blue")
				{
					if (anotherRand == 1 || anotherRand == 0)
					{
						letsAFK(new RSTile(1842, 3229), blueToWestGrave, true);
					}
					else if (anotherRand == 2)
					{
						letsAFK(new RSTile(1882, 3232), blueToObelisk, true);
					}
					else if (anotherRand == 3)
					{
						letsAFK(new RSTile(1807, 3224), null, false);
					}
				}
			}
		}
		return(random(50,100));
	}
	
	public void reset() {
		myLastTeam = currentTeam;
		controlObelisk = null;
		controlWestern = null;
		controlEastern = null;
		currentTeam = null;
		playerPosition = null;
		doWhat = 0;
		countSoulShards = 0;
		inGame = false;
		inWaitArea = false;
		leftSpawn = false;
		countRedTeam = 0;
		countBlueTeam = 0;
		deathCount = 0;
		doRandom = true;
		didSwitch = false;
	}

	private boolean onTile(RSTile tile, String action) {
		try {
			Point location = Calculations.tileToScreen(tile);
			if (location.x == -1 || location.y == -1) return false;
			moveMouse(location, 3, 3);
            //return atMenu(action);
			wait(random(500, 1000));
			if (getMenuItems().get(0).toLowerCase().contains(action.toLowerCase())) {
				clickMouse(true);
				wait(random(1000, 2000));
			} else {
				clickMouse(false);
				if (!atMenu(action)) return false;
			}
			wait(random(500, 1000));
			while (true) {
				if (!getMyPlayer().isMoving()) break;
				wait(random(500, 1000));
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}
    
    int runEnergy = random(30, 50);
    
    private int gEnergy() {
    	return Integer.parseInt(RSInterface.getChildInterface(750, 5).getText());
    }
    
    private boolean energyCheck() {
        try {
            if (gEnergy() >= runEnergy && !isRunning()) {
            	runEnergy = random(35, 65);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }
    
	private int smartJoin(Polygon area) {
		int[] validPlayers = Bot.getClient().getPlayerIndexArray();
		Player[] players = Bot.getClient().getPlayerArray();
		int counter = 0;
		for (int element : validPlayers) {
			if (players[element] == null) {
				continue;
			}
			RSPlayer player = new RSPlayer(players[element]);
			try {
				if (player.getCombatLevel() < 100) 
					continue;
				if (!playerInArea(player, area))
					continue;
				counter++;
			} catch (Exception e) {}
		}
		return counter;
	}
	
	private RSNPC ahhBarricade() {
		int Dist = 2;
		RSNPC closest = null;
		int[] validNPCs = Bot.getClient().getNPCIndexArray();
		NPC[] npcs = Bot.getClient().getNPCArray();

		for (int element : validNPCs) {
			if (npcs[element] == null) {
				continue;
			}
			RSNPC Monster = new RSNPC(npcs[element]);
			try {
				for (int id : barricade) {
					if (id != Monster.getID()) {
						continue;
					}
					int distance = distanceTo(Monster);
					if (distance < Dist) {
						Dist = distance;
						closest = Monster;
					}
				}
			} catch (Exception e) {}
		}
		return closest;
	}
	
	private RSNPC getNearestNPCByID(int hp, int... ids) {
		int Dist = 20;
		RSNPC closest = null;
		int[] validNPCs = Bot.getClient().getNPCIndexArray();
		NPC[] npcs = Bot.getClient().getNPCArray();

		for (int element : validNPCs) {
			if (npcs[element] == null) {
				continue;
			}
			RSNPC Monster = new RSNPC(npcs[element]);
			try {
				for (int id : ids) {
					if (id != Monster.getID()) {
						continue;
					}
					if (Monster.getHPPercent() < hp) {
						continue;
					}
					int distance = distanceTo(Monster);
					if (distance < Dist) {
						Dist = distance;
						closest = Monster;
					}
				}
			} catch (Exception e) {}
		}
		return closest;
	}
	
	public boolean gNPC(RSNPC npc, String action) {
		if (npc == null) return false;
		RSTile tile = npc.getLocation();
		int tileX = npc.getLocation().getX();
		int tileY = npc.getLocation().getY();
		if (!tile.isValid()) return false;
		if (distanceTo(new RSTile(tileX, tileY)) > 5) {
			walkTileMM(new RSTile(tileX + random(-1, 1), tileY + random(-1, 1)));
		}
		return gCharacter(npc, action);
	}
	
	public boolean gCharacter(RSCharacter c, String action) {
		try{
			Point screenLoc = null;
			for (int i = 0; i < 20; i++) {
				screenLoc = c.getScreenLocation();
				if (!c.isValid() || !pointOnScreen(screenLoc)) {
					return false;
				}
				if (getMouseLocation().equals(screenLoc)) break;
				moveMouse(screenLoc);
			}
			screenLoc = c.getScreenLocation();
			if (!getMouseLocation().equals(screenLoc)) return false;
			List<String> items = getMenuItems();
			if (items.size() <= 1) return false;
			if (items.get(0).toLowerCase().contains(action.toLowerCase())) {
				clickMouse(screenLoc, true);
				return true;
			} else {
				clickMouse(screenLoc, false);
				return atMenu(action);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	RSTile ousideBlueEntrance = new RSTile(1880, 3162);
	RSTile ousideRedEntrance = new RSTile(1899, 3162);
	String choice = "4 min";
	boolean doRandom = true;
	int randomChoice = random(1,4);
    
    private boolean listContainsString(List<String> list, String string) {
        try {
            int a;            
            for (a = list.size() - 1; a-- >= 0;) {
                if (list.get(a).contains(string)) {
                    return true;
                }
            }
        } catch (Exception e) {
        }
        return false;
    }
    
    private boolean pickup(int[] id, String itemName) {
    	boolean theReturn = false;
        try {
    	    RSItemTile pickupItem = getGroundItemByID(17, id);
   		    Point itemScreen = Calculations.tileToScreen(pickupItem);
   		    if (pickupItem != null && !getMyPlayer().isMoving()) {
   		    	theReturn = true;
   			    if (pointOnScreen(itemScreen)) {
   			    	moveMouse(itemScreen, 3, 3);
    		    	wait(random(100, 200));
    			   	if (getMenuItems().size() > 1) {
    			   		if (listContainsString(getMenuItems(), itemName)) {
    			   			if (getMenuItems().get(0).contains(itemName)) {
    			  				clickMouse(true);
    		   					wait(random(750,1000));
    		   				} else {
   		    					clickMouse(false);
   		    					wait(random(500,750));
   		    					atMenu(itemName);
  			    				wait(random(750,1000));
    			   			}
    		    		}
   			    	}
   			    }
   		    }
        } catch (Exception e) { }
        return theReturn;
    }
	
	private void doSmartSwitch(String team)
	{
		if (RSInterface.getInterface(837).getChild(9).isValid())
		{
			wait(random(750,1250));
			
			if (doRandom)
			{
				randomChoice = random(1,4);
				if(randomChoice == 1)
					choice = " 4 min";
				else if(randomChoice == 2)
					choice = " 5 min";
				else if(randomChoice == 3)
					choice = " 6 min";
				else if(randomChoice == 4)
					choice = " 7 min";
				doRandom = false;
			}
			
			if (RSInterface.getInterface(837).getChild(9).getText().contains(choice))
			{
				if (team == "Blue")
				{
					while(playerInArea(blueArea) || playerInArea(1870, 3166, 1878, 3158))
					{
						log("[SmartSwitch] Joining the other team");
						if(distanceTo(ousideBlueEntrance) <= 5) 
						{
							if(getCameraAngle() >= 260 && getCameraAngle() <= 280)
							{
								if(!getMyPlayer().isMoving())
									if(onTile(ousideBlueEntrance, "pass"))
										wait(random(1500,3000));
							}
							else
							{
								setCameraRotation(random(260, 280));
								wait(random(500,1000));
							}
						}
						else
						{
							walkTileMM(ousideBlueEntrance);
						}
					}
					wait(random(1500,3000));
					while (!playerInArea(redArea) || !playerInArea(1900, 3157, 1909, 3166))
					{
						if (playerInArea(redArea) || playerInArea(1900, 3157, 1909, 3166))
						{
							didSwitch = true;
							return;
						}
						else
						{
							goRedWaiting();
							wait(random(1500,3000));
						}
					}
				}
				if (team == "Red")
				{
					while(playerInArea(redArea) || playerInArea(1900, 3157, 1909, 3166))
					{
						log("[SmartSwitch] Joining the other team");
						if(distanceTo(ousideRedEntrance) <= 5) 
						{
							if(getCameraAngle() >= 80 && getCameraAngle() <= 100)
							{
								if(!getMyPlayer().isMoving())
									if(onTile(ousideRedEntrance, "pass"))
										wait(random(1500,3000));
							}
							else
							{
								setCameraRotation(random(80, 100));
								wait(random(500,1000));
							}
						}
						else
						{
							if(!getMyPlayer().isMoving())
								walkTileMM(ousideRedEntrance);
						}
					}
					wait(random(1500,3000));
					while (!playerInArea(blueArea) || !playerInArea(1870, 3166, 1878, 3158))
					{
						if (playerInArea(blueArea) || playerInArea(1870, 3166, 1878, 3158))
						{
							didSwitch = true;
							return;
						}
						else
						{
							goBlueWaiting();
							wait(random(1500,3000));
						}
					}
				}
			}
		}
	}
	
	private boolean didSwitch = false;
	
	private void restartSel(int choice)
	{
		if(choice == 1)
		{
			currentTeam = null;
			playerPosition = null;
			inGame = false;
			inWaitArea = false;
			leftSpawn = false;
			countRedTeam = 0;
			countBlueTeam = 0;
			deathCount = 0;
			didSwitch = false;
			doRandom = true;
			log("Please login to start the script.");
			wait(10000);
			return;
		}
		if(choice == 2)
		{
			currentTeam = null;
			playerPosition = null;
			inGame = false;
			inWaitArea = false;
			leftSpawn = false;
			didSwitch = false;
			countRedTeam = 0;
			countBlueTeam = 0;
			deathCount = 0;
			doRandom = true;
			return;
		}
		if(choice == 3)
		{
			checkMessage = null;
			log("Waiting 5 seconds for players to join teams.");
			wait(random(4500,5500));
			currentTeam = null;
			playerPosition = null;
			inGame = false;
			inWaitArea = false;
			leftSpawn = false;
			countRedTeam = 0;
			countBlueTeam = 0;
			deathCount = 0;
			didSwitch = false;
			doRandom = true;
			return;
		}
	}
	
	private void checktheTeam() {
		if (!inGame || leftSpawn)
		{
			
			if (!inGame)
			{
				if (currentTeam == "Red")
				{
					if (playerInArea(redHome) || playerInArea(1958, 3234, 1951, 3244))
					{
						log("The game has started!");
						currentTeam = "Red";
						inGame = true;
						inWaitArea = false;
					}
				}
				if (currentTeam == "Blue")
				{
					if (playerInArea(blueHome) || playerInArea(1823, 3220, 1816, 3230))
					{
						log("The game has started!");
						currentTeam = "Blue";
						inGame = true;
						inWaitArea = false;
					}
				}
				if (currentTeam == null)
				{
					if (playerInArea(blueHome) || playerInArea(1823, 3220, 1816, 3230))
					{
						log("We are in the game - Setting team to Blue!");
						currentTeam = "Blue";
						inGame = true;
						inWaitArea = false;
					}
					if (playerInArea(redHome) || playerInArea(1958, 3234, 1951, 3244))
					{
						log("We are in the game - Setting team to Red!");
						currentTeam = "Red";
						inGame = true;
						inWaitArea = false;
					}
				}
			}
			else 
			{
				if (playerInArea(redHome) || playerInArea(1958, 3234, 1951, 3244))
				{
					leftSpawn = false;
					theLoc = "spawn";
					inGame = true;
					inWaitArea = false;
					return;
				}
				if (playerInArea(blueHome) || playerInArea(1823, 3220, 1816, 3230))
				{
					leftSpawn = false;
					theLoc = "spawn";
					inGame = true;
					inWaitArea = false;
					return;
				}
			}
		}
	}
	
	private void checktheTeam2() {
		if (!inGame && !inWaitArea && currentTeam == null)
		{
			if (playerInArea(redArea))
			{
				currentTeam = "Red";
				log("We are on the Red team.");
				inWaitArea = true;
				redClanCount = 0;
				blueClanCount = 0;
			}
			if (playerInArea(blueArea))
			{
				currentTeam = "Blue";
				log("We are on the Blue team.");
				inWaitArea = true;
				redClanCount = 0;
				blueClanCount = 0;
			}
		}if (!inGame && !inWaitArea && currentTeam == null)
		{
			if (playerInArea(redArea))
			{
				currentTeam = "Red";
				log("We are on the Red team.");
				inWaitArea = true;
				redClanCount = 0;
				blueClanCount = 0;
			}
			if (playerInArea(blueArea))
			{
				currentTeam = "Blue";
				log("We are on the Blue team.");
				inWaitArea = true;
				redClanCount = 0;
				blueClanCount = 0;
			}
		}
	}
	
	private void jointheTeam() {
		if (!inWaitArea && !inGame)
		{
			if (clanChat)
			{
				if (redClanCount > blueClanCount)
				{
					goRedWaiting();
					return;	
				}
				else if (redClanCount < blueClanCount)
				{
					goBlueWaiting();
					return;	
				}
				else
				{
					goBalance();
					return;	
				}
			}
			
			if (smartJoin && (countRedTeam == 0 || countBlueTeam == 0))
			{
				if (myLastTeam == "Blue")
				{
					if (countRedTeam == 0)
					{
						countRedTeam = smartTeamCheck("Red");
						return;	
					}
					if (countBlueTeam == 0)
					{
						countBlueTeam = smartTeamCheck("Blue");
						return;	
					}
				}
				else if (myLastTeam == "Red")
				{
					if (countBlueTeam == 0)
					{
						countBlueTeam = smartTeamCheck("Blue");
						return;	
					}
					if (countRedTeam == 0)
					{
						countRedTeam = smartTeamCheck("Red");
						return;	
					}
				}
				else
				{
					if (countBlueTeam == 0)
					{
						countBlueTeam = smartTeamCheck("Blue");
						return;
					}
					if (countRedTeam == 0)
					{
						countRedTeam = smartTeamCheck("Red");
						return;					
					}
				}
				return;	
			}
			if (smartJoin)
			{
				if (countRedTeam > countBlueTeam)
					goRedWaiting();
				else if (countRedTeam < countBlueTeam)
					goBlueWaiting();
				else if ((countRedTeam == countBlueTeam))
					goBalance();
				else
					log("smartJoin error");
				return;
			}
			
			if (onlyRed)
			{
				goRedWaiting();
				return;
			}
			
			if (onlyBlue)
			{
				goBlueWaiting();
				return;
			}
			
			if (onlyBalance)
			{
				goBalance();
				return;
			}
			
			if (onlyWinners)
			{
				if (lastWon == null)
					goBalance();
				
				if (lastWon == "Red")
					goRedWaiting();
				
				if (lastWon == "Blue")
					goBlueWaiting();
				
				return;
			}

			if (onlyLosers)
			{
				if (lastWon == null)
					goBalance();
				
				if (lastWon == "Red")
					goBlueWaiting();
				
				if (lastWon == "Blue")
					goRedWaiting();
				
				return;
			}
		}
	}
	
	private void inwaitArea() {
		if (!inGame && inWaitArea)
		{
			antiBan();
			wait(random(5000, 10000));
		}
	}
	
	private void leavetheSpawn() {
		if (!leftSpawn)
		{
			if (playerInArea(redHome) || playerInArea(1958, 3234, 1951, 3244))
			{
				leftSpawn = leaveSpawn("RedStart");
				theLoc = "spawn";
				return;
			}
			if (playerInArea(blueHome) || playerInArea(1823, 3220, 1816, 3230))
			{
				leftSpawn = leaveSpawn("BlueStart");
				theLoc = "spawn";
				return;
			}
			if (playerInArea(eastGraveyard))
			{
				leftSpawn = leaveSpawn("EastGraveyard");
				theLoc = "eastGrave";
				return;
			}
			if (playerInArea(westGraveyard))
			{
				leftSpawn = leaveSpawn("WestGraveyard");
				theLoc = "westGrave";
				return;
			}
			
			//BLUE SPAWN
			if (playerInArea(1815, 3220, 1808, 3229))
			{
				leftSpawn = true;
				log("We have left the spawn!");
				currentTeam = "Blue";
				playerPosition = "OutsideSpawn";
				return;
			}
			//RED SPAWN
			if (playerInArea(1966, 3233, 1959, 3242))
			{
				leftSpawn = true;
				log("We have left the spawn!");
				currentTeam = "Red";
				playerPosition = "OutsideSpawn";
				return;
			}
			//WEST GRAVEYARD
			if (getMyPlayer().getLocation().getX() == 1842 && getMyPlayer().getLocation().getY() == 3220)
			{
				leftSpawn = true;
				log("We have left the spawn!");
				playerPosition = "WestGrave";
				return;
			}
			//EAST GRAVEYARD
			if (getMyPlayer().getLocation().getX() == 1933 && getMyPlayer().getLocation().getY() == 3243)
			{
				leftSpawn = true;
				log("We have left the spawn!");
				playerPosition = "EastGrave";
				return;
			}
			
			return;
		}
	}
	
	private void runthisfirst() {
		if(!isLoggedIn()) {
			restartSel(1);
		}
		
		if (smartSwitch && !didSwitch)
		{
			doSmartSwitch(currentTeam);
		}
		
		if ((playerInArea(1899, 3145, 1880, 3190) || playerInArea(outside)) && (inWaitArea || inGame))
		{
			restartSel(2);
		}
		else
			antiBan2();
		
		try
		{
			if (checkMessage.contains("you are dead"))
			{
				checkMessage = null;
				log("Waiting 15 seconds for ghost-mode to deactivate.");
				wait(random(14000, 15000));
				return;
			}
	
			if (checkMessage.contains("participation") && smartJoin)
			{
				restartSel(3);
				return;
			}
		}
		catch (NullPointerException e)
		{
		
		}
		
		if (energyCheck()) {
            setRun(true);
            wait(random(750,1000));
            return;
        }
	}
	
	private void letsFight(RSTile tile, RSTile[] path, int[] monsterID, String monsterStr) {
		if (!leftSpawn)
			return;
		if (distanceTo(tile) <= 15)
		{
			if (getMyPlayer().isInCombat() || getMyPlayer().isMoving() || getMyPlayer().getInteracting() != null)
			{
				if (getMyPlayer().isInCombat())
					antiBan2();
				return;
			}
			
			gNPC(getNearestNPCByID(20, monsterID), monsterStr);
			
			return;
		}
		if(!getMyPlayer().isMoving() && getMyPlayer().getInteracting() == null)
		{
			if (gNPC(ahhBarricade(), "Attack"))
				wait(random(2000,4000));
		}
		if(!getMyPlayer().isMoving() || distanceTo(getDestination()) <= random(4, 7))
			walkPathMM(randomizePath(path, 2, 2), 17);
	}
	
	private void letsAFK(RSTile tile, RSTile[] path, boolean usePath) {
		if (!leftSpawn)
			return;
		if (usePath) {
			if (distanceTo(tile) >= 15)
			{
				if(!getMyPlayer().isMoving() && getMyPlayer().getInteracting() == null)
				{
					if (gNPC(ahhBarricade(), "Attack"))
						wait(random(2000,4000));
				}
				if(!getMyPlayer().isMoving() || distanceTo(getDestination()) <= random(4, 7))
					walkPathMM(randomizePath(path, 2, 2), 17);
			}
			else
			{
				antiBan2();
				wait(random(4000,6000));
				randomAFK();
				return;
			}
		} else {
			if (distanceTo(tile) >= 15)
			{
				if(!getMyPlayer().isMoving() && getMyPlayer().getInteracting() == null)
				{
					if (gNPC(ahhBarricade(), "Attack"))
						wait(random(2000,4000));
				}
				if(!getMyPlayer().isMoving() || distanceTo(getDestination()) <= random(4, 7))
					walkTileMM(new RSTile(tile.getX() + random(-3,3), tile.getY() + random(-3,3)));
			}
			else
			{
				antiBan2();
				wait(random(4000,6000));
				randomAFK();
				return;
			}
		}
	}
	
	private int anotherRand = random(1,4);
	
	private int randomAFK() {
		int randomNum = random(1, 20);

		if (randomNum == 5)
		{
			if (distanceTo(new RSTile(1933, 3243)) <= 10)
			{
				walkTileMM(new RSTile(1933 + random(-5,5), 3243 + random(-5,5)));
				return random(50,150);
			}
			if (distanceTo(new RSTile(1842, 3229)) <= 10)
			{
				walkTileMM(new RSTile(1842 + random(-5,5), 3229 + random(-5,5)));
				return random(50,150);
			}
	        if ((anotherRand == 0 || anotherRand == 1) && currentTeam == "Blue")
	        {
	        	walkTileMM(new RSTile(1842 + random(-5,5), 3229 + random(-5,5)));
	        	return random(50,150);
	        }
	        if ((anotherRand == 0 || anotherRand == 1) && currentTeam == "Red")
	        {
	        	walkTileMM(new RSTile(1933 + random(-5,5), 3243 + random(-5,5)));
	        	return random(50,150);
	        }
	        if (anotherRand == 2 && currentTeam == "Blue")
	        {
	        	walkTileMM(new RSTile(1887 + random(-5,5), 3232 + random(-5,5)));
	        	return random(50,150);
	        }
	        if (anotherRand == 2 && currentTeam == "Red")
	        {
	        	walkTileMM(new RSTile(1882 + random(-5,5), 3232 + random(-5,5)));
	        	return random(50,150);
	        }
	        if (anotherRand == 3 && currentTeam == "Blue")
	        {
	        	walkTileMM(new RSTile(1807 + random(-5,5), 3224 + random(-5,5)));
	        	return random(50,150);
	        }
	        if (anotherRand == 3 && currentTeam == "Red")
	        {
	        	walkTileMM(new RSTile(1967 + random(-5,5), 3238 + random(-5,5)));
	        	return random(50,150);
	        }
		}
		
		return 500;
	}
	
	private int antiBan2() {
		int randomNum = random(1, 18);

        switch (randomNum) {
            case 1:
                wait(random(1000, 1500));
                break;

            case 2:
                    int x = random(0, 750);
                    int y = random(0, 500);
                    moveMouse(0, 0, x, y);
                return random(1000, 1500);

            case 3:
                if (getCurrentTab() != TAB_INVENTORY) {
                    openTab(TAB_INVENTORY);
                    return random(500, 750);
                } else {
                    return random(500, 750);
                }

            case 4:
            	if (random(1, 60) == 30)
            	{
	                if (getMyPlayer().isMoving()) {
	                    return random(750, 1000);
	                }
	                if (getCurrentTab() != TAB_STATS) {
	                    openTab(TAB_STATS);
	                }
	                moveMouse(560, 230, 40, 180);
	                return random(3000, 6000);
            	}

            case 5:
                if (random(1, 3) == 2) {
                    int angle = getCameraAngle() + random(-90, 90);
                    if (angle < 0) {
                        angle = 0;
                    }
                    if (angle > 359) {
                        angle = 0;
                    }

                    setCameraRotation(angle);
                return random(500, 750);
                }
          }
		return 500;
	}

	private boolean leaveSpawn(String area)
	{
		if(area == "BlueStart") 
		{
			if(distanceTo(new RSTile(1815, 3225)) <= 3) 
			{
				if(getCameraAngle() >= 80 && getCameraAngle() <= 100)
				{
					if(!getMyPlayer().isMoving())
					{
						onTile(new RSTile(1815, 3225), "Pass Blue barrier");
						wait(random(1000, 2000));
					}
				}
				else
				{
					setCameraRotation(random(80, 100));
					return false;
				}
			}
			else if(!getMyPlayer().isMoving())
			{
				walkTileMM(new RSTile(1815, 3225));
				return false;
			}
			if (!playerInArea(1823, 3220, 1816, 3230) || getMyPlayer().getLocation().getX() == 1815 && getMyPlayer().getLocation().getY() == 3225)
			{
				log("We have left the spawn!");
				currentTeam = "Blue";
				playerPosition = "OutsideSpawn";
				return true;
			}
		}
		if(area == "RedStart") 
		{
			if(distanceTo(new RSTile(1959, 3239)) <= 3) 
			{
				if(getCameraAngle() >= 260 && getCameraAngle() <= 280)
				{
					if(!getMyPlayer().isMoving())
					{
						onTile(new RSTile(1959, 3239), "Pass Red barrier");
						wait(random(1000, 2000));
					}
				}
				else
				{
					setCameraRotation(random(260, 280));
					return false;
				}
			}
			else if(!getMyPlayer().isMoving())
			{
				walkTileMM(new RSTile(1959, 3239));
				return false;
			}
			if (!playerInArea(1958, 3234, 1951, 3244) || getMyPlayer().getLocation().getX() == 1959 && getMyPlayer().getLocation().getY() == 3239)
			{
				log("We have left the spawn!");
				currentTeam = "Red";
				playerPosition = "OutsideSpawn";
				return true;
			}
		}
		if(area == "EastGraveyard") 
		{
			if(getCameraAngle() >= 170 && getCameraAngle() <= 190)
			{
				if(!getMyPlayer().isMoving())
				{
					if (onTile(new RSTile(1933, 3243), "Pass Red barrier"))
						currentTeam = "Red";
					if (onTile(new RSTile(1933, 3243), "Pass Blue barrier"))
						currentTeam = "Blue";
					wait(random(1000, 2000));
				}
			}
			else
			{
				setCameraRotation(random(170, 190));
				return false;
			}
			if (!playerInArea(1934,3244,1932,3246) || getMyPlayer().getLocation().getX() == 1933 && getMyPlayer().getLocation().getY() == 3243)
			{
				log("We have left the spawn!");
				playerPosition = "EastGrave";
				return true;
			}
		}
		if(area == "WestGraveyard") 
		{
			if(getCameraAngle() >= 0 && getCameraAngle() <= 10 || getCameraAngle() >= 350 && getCameraAngle() <= 360)
			{
				if(!getMyPlayer().isMoving())
				{
					if (onTile(new RSTile(1842, 3220), "Pass Red barrier"))
						currentTeam = "Red";
					if (onTile(new RSTile(1842, 3220), "Pass Blue barrier"))
						currentTeam = "Blue";
					wait(random(1000, 2000));
				}
			}
			else
			{	
				int a = random(1,3);
				if (a == 1)
					setCameraRotation(random(350, 360));
				else
					setCameraRotation(random(0, 10));
				return false;
			}
			if (getMyPlayer().getLocation().getX() == 1842 && getMyPlayer().getLocation().getY() == 3220)
			{
				log("We have left the spawn!");
				playerPosition = "WestGrave";
				return true;
			}
		}
		return false;
	}
	
	private int antiBan() {
		int randomNum = random(1, 10);

        switch (randomNum) {
            case 1:
                wait(random(1000, 1500));
                break;

            case 2:
                    int x = random(0, 750);
                    int y = random(0, 500);
                    moveMouse(0, 0, x, y);
                return random(1000, 1500);

            case 3:
                if (getCurrentTab() != TAB_INVENTORY) {
                    openTab(TAB_INVENTORY);
                    return random(500, 750);
                } else {
                    return random(500, 750);
                }

            case 4:
                if (getMyPlayer().isMoving()) {
                    return random(750, 1000);
                }
                    if (getCurrentTab() != TAB_STATS) {
                        openTab(TAB_STATS);
                    }
                    moveMouse(560, 230, 40, 180);
                    return random(5000, 8000);

            case 5:
                if (random(1, 3) == 2) {
                    int angle = getCameraAngle() + random(-90, 90);
                    if (angle < 0) {
                        angle = 0;
                    }
                    if (angle > 359) {
                        angle = 0;
                    }

                    setCameraRotation(angle);
                return random(500, 750);
                }
            case 6:
                if (playerInArea(blueArea) || currentTeam == "Blue") {
                	int arrayLength = randomBlueX.length - 1;
                	int randomTile = random(0, arrayLength);
                    walkTileMM(new RSTile(randomBlueX[randomTile], randomBlueY[randomTile]));
                }
                if (playerInArea(redArea) || currentTeam == "Red") {
                	int arrayLength = randomRedX.length - 1;
                	int randomTile = random(0, arrayLength);
                	walkTileMM(new RSTile(randomRedX[randomTile], randomRedY[randomTile]));
                }
          }
		return 500;
	}
	
	private int getSlayerLevel() {
		int selectSlayer = Skills.getStatIndex("Slayer");
		return skills.getCurrentSkillLevel(selectSlayer);
	}
	
	private int goRedWaiting(){
		if(distanceTo(RedEntrance) <= 5) 
		{
			if(getCameraAngle() >= 260 && getCameraAngle() <= 280)
			{
				if(!getMyPlayer().isMoving())
				{
					if (!playerInArea(redArea) || !playerInArea(1900, 3157, 1909, 3166))
						onTile(RedEntrance, "pass");
					wait(random(800, 1000));
					if (leftEarly())
					{
						int waitTime = howLong();
						log("We must wait " + waitTime + " more minutes!");
						if (waitTime > 5)
							wait(random(120000, 180000));
						else if (waitTime > 3)
							wait(random(60000, 120000));
						else
							wait(random(30000, 60000));
						return random(50, 150);
					}
					while (atInterface(RSInterface.getInterface(211).getChild(3)) || atInterface(RSInterface.getInterface(228).getChild(2)))
					{
						wait(random(800, 1000));
						if (atInterface(RSInterface.getInterface(211).getChild(3)))
						{
							clickMouse(190 + random(0, 140), 445 + random(0,15), true);
						}
						wait(random(800, 1000));
						if (atInterface(RSInterface.getInterface(228).getChild(2)))
						{
							clickMouse(220 + random(0, 80), 395 + random(0,15), true);
						}
						wait(random(800, 1000));
					}
					wait(random(1000, 2000));
				}
			}
			else
			{
				setCameraRotation(random(260, 280));
				return random(50, 150);
			}
		}
		else if(!getMyPlayer().isMoving() || distanceTo(getDestination()) <= random(4, 7))
		{
			walkPathMM(randomizePath(ToRed, 2, 2), 17);
			return random(50, 150);
		}
		
		if (playerInArea(redArea))
		{
			inWaitArea = true;
			log("We have joined the Red team!");
			currentTeam = "Red";
			wait(random(1000, 2000));
		}
		
		return random(50, 150);
	}
	
	private boolean leftEarly()
	{
		if (RSInterface.getChildInterface(211, 1).isValid() && RSInterface.getChildInterface(211, 1).getText().contains("left a game"))
		{
			return true;
		}
		else
			return false;
	}
	
	private int howLong()
	{
		String getLine = RSInterface.getChildInterface(211, 1).getText();
		String subLine = getLine.substring(getLine.indexOf("wait ") + 5, getLine.indexOf(" minutes"));
		return Integer.parseInt(subLine);
	}
	
	private int goBlueWaiting(){
		if(distanceTo(BlueEntrance) <= 5) 
		{
			if(getCameraAngle() >= 80 && getCameraAngle() <= 100)
			{
				if(!getMyPlayer().isMoving())
				{
					if (!playerInArea(blueArea) || !playerInArea(1870, 3166, 1878, 3158))
						onTile(BlueEntrance, "pass");
					wait(random(800, 1000));
					if (leftEarly())
					{
						int waitTime = howLong();
						log("We must wait " + waitTime + " more minutes!");
						if (waitTime > 5)
							wait(random(120000, 180000));
						else if (waitTime > 3)
							wait(random(60000, 120000));
						else
							wait(random(30000, 60000));
						return random(50, 150);
					}
					while (atInterface(RSInterface.getInterface(211).getChild(3)) || atInterface(RSInterface.getInterface(228).getChild(2)))
					{
						wait(random(800, 1000));
						if (atInterface(RSInterface.getInterface(211).getChild(3)))
						{
							clickMouse(190 + random(0, 140), 445 + random(0,15), true);
						}
						wait(random(800, 1000));
						if (atInterface(RSInterface.getInterface(228).getChild(2)))
						{
							clickMouse(220 + random(0, 80), 395 + random(0,15), true);
						}
						wait(random(800, 1000));
					}
					wait(random(1000, 2000));
				}
			}
			else
			{
				setCameraRotation(random(80, 100));
				return random(50, 150);
			}
		}
		else if(!getMyPlayer().isMoving() || distanceTo(getDestination()) <= random(4, 7))
		{
			walkPathMM(randomizePath(ToBlue, 2, 2), 17);
			return random(50, 150);
		}
		
		if (playerInArea(blueArea))
		{
			inWaitArea = true;
			log("We have joined the Blue team!");
			currentTeam = "Blue";
			wait(random(1000, 2000));
		}
		
		return random(50, 150);
	}

	int trys = 0;
	
	public int smartTeamCheck(String team){
		
		if (team == "Red")
		{
			if(distanceTo(RedEntrance) <= 4) 
			{
				if (smartJoin(redArea) == 0)
					return 1;
				else
					return smartJoin(redArea);
			}
			else if(!getMyPlayer().isMoving())
			{
				walkPathMM(randomizePath(ToRed, 2, 2), 17);
				return 0;
			}
			return 0;
		}
		
		if (team == "Blue")
		{
			if(distanceTo(BlueEntrance) <= 4) 
			{
				if (smartJoin(redArea) == 0)
					return 1;
				else
					return smartJoin(blueArea);
			}
			else if(!getMyPlayer().isMoving())
			{
				walkPathMM(randomizePath(ToBlue, 2, 2), 17);
				return 0;
			}
			return 0;
		}
		return 0;
	}

	public int goBalance(){
		if(distanceTo(BalanceEntrance) <= 4) 
		{
			if(!getMyPlayer().isMoving())
			{
				onTile(BalanceEntrance, "join-team");
				wait(random(800, 1000));
				if (leftEarly())
				{
					int waitTime = howLong();
					log("We must wait " + waitTime + " more minutes!");
					if (waitTime > 5)
						wait(random(120000, 180000));
					else if (waitTime > 3)
						wait(random(60000, 120000));
					else
						wait(random(30000, 60000));
					return random(50, 150);
				}
				while (atInterface(RSInterface.getInterface(211).getChild(3)) || atInterface(RSInterface.getInterface(228).getChild(2)))
				{
					wait(random(800, 1000));
					if (atInterface(RSInterface.getInterface(211).getChild(3)))
					{
						clickMouse(190 + random(0, 140), 445 + random(0,15), true);
					}
					wait(random(800, 1000));
					if (atInterface(RSInterface.getInterface(228).getChild(2)))
					{
						clickMouse(220 + random(0, 80), 395 + random(0,15), true);
					}
					wait(random(800, 1000));
				}
				wait(random(1000, 2000));
			}
		}
		else if(!getMyPlayer().isMoving())
		{
			walkPathMM(randomizePath(ToBalance, 2, 2), 17);
			return random(50, 150);
		}
		
		if (playerInArea(redArea))
		{
			inWaitArea = true;
			log("We have joined the Red team!");
			currentTeam = "Red";
			wait(random(1000, 2000));
		}
		
		if (playerInArea(blueArea))
		{
			inWaitArea = true;
			log("We have joined the Blue team!");
			currentTeam = "Blue";
			wait(random(1000, 2000));
		}
		
		return random(50, 150);
	}

	String lastmessage = null;
	String checkMessage = null;

	public void serverMessageRecieved(ServerMessageEvent e) {
		String messageEvent = e.getMessage();
		
		if (messageEvent == lastmessage && (!messageEvent.contains("you are dead") || !messageEvent.contains("gave you some soul fragments")))
		{
			return;
		}
		
		lastmessage = e.getMessage();
		checkMessage = e.getMessage();
		
		if (messageEvent.contains("you are dead"))  
		{
			log("You have died. All soul fragments were lost."); 
			countSoulShards = 0;
			leftSpawn = false;
			playerPosition = "Spawn";
			anotherRand = random(1,4);
			deathCount++;
		}
		if (messageEvent.contains("gave you some soul fragments"))  
		{
			log("You have gained some soul fragments."); 
			countSoulShards++;
		}
		if (messageEvent.contains("participation"))  
		{
			gamesCompleted++;
			if (messageEvent.contains("3 Zeal")) 
			{
				zealGained += 3;
				log("We have gained 3 Zeal.");
			}
			else if (messageEvent.contains("2 Zeal")) 
			{
				zealGained += 2;
				log("We have gained 2 Zeal.");
			}
			else if (messageEvent.contains("1 Zeal")) 
			{
				zealGained += 1;
				log("We have gained 1 Zeal.");
			}
			if (messageEvent.contains("was drawn"))
			{
				lastWon = null;
				log("It was a draw!");
				reset();
			}
			else if (messageEvent.contains("blue"))
			{
				lastWon = "Blue";
				log("Blue team won!");
				reset();
			}
			else if (messageEvent.contains("red")) 
			{
				lastWon = "Red";
				log("Red team won!");
				reset();
			}
		}
		if (messageEvent.contains("eastern graveyard"))  
		{
			if (messageEvent.contains("lost"))
			{
				if (messageEvent.contains("red"))
				{
					log("Red lost control of Eastern Graveyard!"); 
					controlEastern = null;
				}
				else if (messageEvent.contains("blue"))
				{
					log("Blue lost control of Eastern Graveyard!");
					controlEastern = null;
				}
			}
			else if (messageEvent.contains("taken"))
			{
				if (messageEvent.contains("red"))
				{
					log("Red took control of Eastern Graveyard!"); 
					controlEastern = "Red";
				}
				else if (messageEvent.contains("blue"))
				{
					log("Blue took control of Eastern Graveyard!"); 
					controlEastern = "Blue";
				}
			}
		}
		if (messageEvent.contains("western graveyard"))  
		{
			if (messageEvent.contains("lost"))
			{
				if (messageEvent.contains("red"))
				{
					log("Red lost control of Western Graveyard!"); 
					controlWestern = null;
				}
				else if (messageEvent.contains("blue"))
				{
					log("Blue lost control of Western Graveyard!");
					controlWestern = null;
				}
			}
			else if (messageEvent.contains("taken"))
			{
				if (messageEvent.contains("red"))
				{
					log("Red took control of Western Graveyard!"); 
					controlWestern = "Red";
				}
				else if (messageEvent.contains("blue"))
				{
					log("Blue took control of Western Graveyard!"); 
					controlWestern = "Blue";
				}
			}
		}
		if (messageEvent.contains("soul obelisk"))  
		{
			if (messageEvent.contains("lost"))
			{
				if (messageEvent.contains("red"))
				{
					log("Red lost control of Soul Obelisk!"); 
					controlObelisk = null;
				}
				else if (messageEvent.contains("blue"))
				{
					log("Blue lost control of Soul Obelisk!");
					controlObelisk = null;
				}
			}
			else if (messageEvent.contains("taken"))
			{
				if (messageEvent.contains("red"))
				{
					log("Red took control of Soul Obelisk!"); 
					controlObelisk = "Red";
				}
				else if (messageEvent.contains("blue"))
				{
					log("Blue took control of Soul Obelisk!"); 
					controlObelisk = "Blue";
				}
			}
		}
	}
	
	int xpgained = 0;
	int skillATT = 0;
	int skillSTR = 0;
	int skillDEF = 0;
	int skillRNG = 0;
	int skillMAG = 0;
	int skillHIT = 0;
	int skillSLY = 0;
	int skillPRY = 0;
	int[] skillArray;
	String[] nameArray;
	
	private boolean setupSkills()
	{
		skillATT = skills.getCurrentSkillExp(Skills.getStatIndex("attack"));
		skillSTR = skills.getCurrentSkillExp(Skills.getStatIndex("strength"));
		skillDEF = skills.getCurrentSkillExp(Skills.getStatIndex("defence"));
		skillRNG = skills.getCurrentSkillExp(Skills.getStatIndex("range"));
		skillMAG = skills.getCurrentSkillExp(Skills.getStatIndex("magic"));
		skillHIT = skills.getCurrentSkillExp(Skills.getStatIndex("hitpoints"));
		skillSLY = skills.getCurrentSkillExp(Skills.getStatIndex("slayer"));
		skillPRY = skills.getCurrentSkillExp(Skills.getStatIndex("prayer"));
		skillArray = new int[]{skillATT, skillSTR, skillDEF, skillHIT, skillRNG, skillMAG, skillPRY, skillSLY};
		nameArray = new String[]{"Attack", "Strength", "Defense", "Hitpoints", "Range", "Magic", "Prayer", "Slayer"};
		
		return false;
	}

	boolean setupSkills = false;
	
	public void onRepaint(Graphics g) {
        long runTime = 0;
        long seconds = 0;
        long minutes = 0;
        long hours = 0;
        
        runTime = System.currentTimeMillis( ) - scriptStartTime;
    	seconds = runTime / 1000;
    	if ( seconds >= 60 ) {
    		minutes = seconds / 60;
    		seconds -= (minutes * 60);
    	}
    	if ( minutes >= 60 ) {
    		hours = minutes / 60;
    		minutes -= (hours * 60);
    	}
    	
    	if (!setupSkills)
    	{
    		setupSkills();
    		setupSkills = true;
    	}
		
    	int coordCount = 0;
    	
        if(getCurrentTab() == TAB_INVENTORY) 
        {
        	g.setColor(new Color(0, 0, 0, 100));	
        	g.fillRoundRect(555, 210, 175, 250, 10, 10);
        	g.setColor(Color.WHITE);
        		
        	int[] coords = new int[] {225, 240, 255, 270, 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450};
        	
	        g.drawString(getName() + " v" + getVersion(), 561, coords[0]);
	        g.drawString("Run Time: " + hours + ":" + minutes + ":" + seconds, 561, coords[1]);
	        g.drawString("Games Completed: " + gamesCompleted, 561, coords[2]);
	        g.drawString("Zeal Gained: " + zealGained, 561, coords[3]);
	        
			skillATT = skills.getCurrentSkillExp(Skills.getStatIndex("attack"));
			skillSTR = skills.getCurrentSkillExp(Skills.getStatIndex("strength"));
			skillDEF = skills.getCurrentSkillExp(Skills.getStatIndex("defence"));
			skillRNG = skills.getCurrentSkillExp(Skills.getStatIndex("range"));
			skillMAG = skills.getCurrentSkillExp(Skills.getStatIndex("magic"));
			skillHIT = skills.getCurrentSkillExp(Skills.getStatIndex("hitpoints"));
			skillSLY = skills.getCurrentSkillExp(Skills.getStatIndex("slayer"));
			skillPRY = skills.getCurrentSkillExp(Skills.getStatIndex("prayer"));
			int[] newSkillArray = new int[]{skillATT, skillSTR, skillDEF, skillHIT, skillRNG, skillMAG, skillPRY, skillSLY};
	        
	        for (int i = 0; i < 8; i++)
	        {
	        	xpgained = newSkillArray[i] - skillArray[i];
	        	if (xpgained == 0)
	        		continue;
	        	g.drawString(nameArray[i] + " XP: " + xpgained, 561, coords[(5 + coordCount)]);
	        	coordCount++;
	        }
	        
	        g.drawString("Team Method: " + teamMethod, 561, coords[14]);
	        g.drawString("In-Game Action: " + inGameMethod, 561, coords[15]);
        }
        
	}
	
	public boolean playerInArea(RSPlayer player, Polygon area) 
	{
		return area.contains(new Point(player.getLocation().getX(), player.getLocation().getY()));
	}
	
	public boolean playerInArea(Polygon area) 
	{
		return area.contains(new Point(getMyPlayer().getLocation().getX(), getMyPlayer().getLocation().getY()));
	}
	
	public boolean playerInArea(int maxX, int minY, int minX, int maxY) 
	{ 
		int x = getMyPlayer().getLocation().getX(); 
		int y = getMyPlayer().getLocation().getY(); 
		if (x >= minX && x <= maxX && y >= minY && y <= maxY) 
		{ 
			return true; 
		} 
		return false; 
	}
}